package com.jasonzqshen.ifm.utils;

import java.util.LinkedList;

public class EventHandler<Sender, Args> {
    private LinkedList<Delegater<Sender, Args>> delegaters;
    
    public EventHandler() {
        delegaters = new LinkedList<Delegater<Sender, Args>>();
    }

    /**
     * Add delegate
     * 
     * @param delegater
     */
    public void addDelegate(Delegater<Sender, Args> delegater) {
        this.delegaters.add(delegater);
    }

    /**
     * Begin asyn invoke the delegate. 
     */
    public void beginInvoke(final Sender object, final Args args) {
        LinkedList<Thread> threads = new LinkedList<Thread>();
        for (final Delegater<Sender, Args> delegater : delegaters) {
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    delegater.execute(object, args);
                }
            };

            Thread newThread = new Thread(runnable);
            newThread.start();
            
            threads.add(newThread);
        }

        // waiting for all thread execute
        boolean allStop = false;
        while (allStop == false) {
            allStop = true;
            for (Thread thread : threads) {
                if (thread.getState() != Thread.State.TERMINATED) {
                    allStop = false;
                    break;
                }
            }
        }
    }
}
